import axios from "axios";
import { Toast } from "react-vant";
import { getDeviceCode } from ".";

const http = axios.create();
http.defaults.timeout = 10000;

// 请求拦截
http.interceptors.request.use(
  async (config: any) => {
    const openid = localStorage.getItem("openid") || undefined;
    const userId = localStorage.getItem("userId") || undefined;

    //如果存在，为deviceCode 设置openid
    if (openid) window.deviceCode = openid;

    //添加设备code
    if (!window.deviceCode) {
      const deviceCode = await getDeviceCode();
      window.deviceCode = deviceCode;
    }

    config.headers["sid"] = window.deviceCode || "";
    return config;
  },
  (error: any) => {
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// 响应拦截器
http.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res?.state === "fail") res?.msg && Toast(res?.msg);
    return res;
  },
  (error) => {
    return Promise.reject(error);
  }
);

export default http;
